package example.demo.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

@Slf4j
public class SyncExceptionTest {
    static Thread b;
    static Thread a;

    public static void a() {
        //在try {  synchronized{}  }catch(Exception e){ } 会释放锁，一定要在同步代码块里面捕获异常
        synchronized (SyncExceptionTest.class) {
            //确保做有用的唤醒线程B的操作
            while (b == null) {
            }
            LockSupport.unpark(b);
            log.info(Thread.currentThread().getName() + "拿到锁---唤醒" + b.getName());
            int i = 1 / 0;
            /* try {
                int i = 1 / 0;
            } catch (Exception exception) {
                exception.printStackTrace();
            }*/
            try {
                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void b() {
        b = Thread.currentThread();
        LockSupport.park();
        synchronized (SyncExceptionTest.class) {
            log.info(Thread.currentThread().getName() + "---拿到锁");
        }
    }

    public static void main(String[] args) {
        new Thread(SyncExceptionTest::a, "AAA").start();
        new Thread(SyncExceptionTest::b, "BBB").start();
    }
}
